package com.witmore.neutron.ai.cognitive.service;

import org.jetbrains.annotations.NotNull;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Description: ChatMemoryRepositoryCustom
 * Author: 豆子高
 * Date: 2025/6/6 18:07
 */
@Service
public class CustomChatMemoryRepository implements ChatMemoryRepository {


    @Autowired
    private AgentService agentService;

    private final JdbcChatMemoryRepository delegate;

    public CustomChatMemoryRepository(JdbcChatMemoryRepository delegate) {
        this.delegate = delegate;
    }


    @NotNull
    @Override
    public List<String> findConversationIds() {
        return delegate.findConversationIds();
    }

    @NotNull
    @Override
    public List<Message> findByConversationId(@NotNull String conversationId) {
        Assert.hasText(conversationId, "conversationId cannot be null or empty");
        return agentService.findSessionRecordById(conversationId);
    }

    @Override
    public void saveAll(@NotNull String conversationId, @NotNull List<Message> messages) {
        Assert.hasText(conversationId, "conversationId cannot be null or empty");
        Assert.notNull(messages, "messages cannot be null");
        Assert.noNullElements(messages, "messages cannot contain null elements");
        // 需要过滤一下messages消息 去除库内已有数据 根据元数据值 key="db_id"来去重
        agentService.saveAll(conversationId, messages);
    }


    @Override
    public void deleteByConversationId(@NotNull String conversationId) {
        Assert.hasText(conversationId, "conversationId cannot be null or empty");
        delegate.deleteByConversationId(conversationId);
    }

}
